package pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.jinyou.utils.common.ValidateUtil;
import net.sf.json.JSONObject;
import o2o.dao.PO.common.ResultInfo;
import o2o.web.actions.pay.OrderPay;
import pay.ChannelUtils;
import pay.TradeStatusUtils;
import pay.alipay.utils.AlipayCore;
import pay.alipay.utils.SignUtils;
import pay.alipay.utils.UtilDate;
import pay.config.AlipayConfig;
import pay.dao.QueryResult;
import pay.exceptions.DataEmptyException;
import pay.exceptions.QueryExcetion;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static pay.config.AlipayConfig.format;

/**
 * Created with IntelliJ IDEA.
 * User: Jahnke [1029777564@qq.com]
 * Date: 2017-01-07 23:42
 * 阿里的支付工具
 */
public class AliPayUtils {
    private AliPayUtils() {
    }

    private static AliPayUtils single = new AliPayUtils();

    public static AliPayUtils getInstance() {
        if (single == null) {
            single = new AliPayUtils();
        }
        return single;
    }

    /**
     * 直接支付
     * Jahnke 2017年1月7日 23:53:22
     *
     * @param orderCode  订单号
     * @param pay        支付金额
     * @param activeTime 默认30m 订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
     * @param subject    商品名称
     * @param body       商品详情
     * @return
     */
    public String direct_pay(String orderCode, float pay, String activeTime, String subject, String body) {
        String[] parameters = {
                "service=\"create_direct_pay_by_user\"",                                 //固定值（即时到帐）
                "partner=\"" + AlipayConfig.partner + "\"",                                 //合作身份者ID（16位）
                "_input_charset=\"" + AlipayConfig.input_charset + "\"",
                "notify_url=\"" + AlipayConfig.notify_url + "\"",                           //服务器异步通知页面路径	  不可为空
                "out_trade_no=\"" + orderCode + "\"",                                       //商户内部订单号
                "subject=\"" + (subject == null || subject.equals("") ? "商品" : subject) + "\"",      //测试
                "payment_type=\"" + AlipayConfig.payment_type + "\"",                       //支付类型	-固定值
                "seller_id=\"" + AlipayConfig.partner + "\"",                               //seller_id是以2088开头的纯16位数字。
                "seller_email=\"" + AlipayConfig.seller_id + "\"",                          //卖家支付宝账号
                "total_fee=\"" + pay + "\"",                                                //该笔订单的资金总额，单位为RMB-Yuan。取值范围为[0.01，100000000.00]，精确到小数点后两位。
                "body=\"" + (body == null || body.equals("") ? "商品描述" : body) + "\"",                                                    //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
                "qr_pay_mode=\"1\"",                                                        //1：订单码-前置模式，对应iframe宽度不能小于300px，高度不能小于600px；
                //订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
                "it_b_pay=\"" + (activeTime == null || activeTime.equals("") ? "30m" : activeTime) + "\""
        };

        String signOrderUrl = SignUtils.signAllString(parameters);
        System.out.println("ali-redirect签名：" + signOrderUrl);
        return signOrderUrl;
    }

    /**
     * 移动支付
     * Jahnke 2017年1月7日 23:53:14
     *
     * @param orderCode  订单号
     * @param pay        支付金额
     * @param activeTime 默认30m 订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
     * @param subject    商品名称
     * @param body       商品详情
     * @return
     */
    public String mobile_pay(String orderCode, float pay, String activeTime, String subject, String body) throws UnsupportedEncodingException, AlipayApiException {
        //公共参数
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_id", AlipayConfig.app_id);
        map.put("method", "alipay.trade.app.pay");
        map.put("format", format);
        map.put("charset", AlipayConfig.input_charset);
        map.put("sign_type", AlipayConfig.sign_type);
        map.put("timestamp", UtilDate.getDateFormatter());
        map.put("version", "1.0");
        map.put("notify_url", AlipayConfig.notify_url);

        Map<String, String> m = new HashMap<String, String>();
        m.put("body", body == null || body.equals("") ? "商品描述" : body);
        m.put("subject", (subject == null || subject.equals("") ? "商品" : subject));
        m.put("out_trade_no", orderCode);
        m.put("timeout_express", activeTime == null || activeTime.equals("") ? "30m" : activeTime);
        m.put("total_amount", String.valueOf(pay));
        m.put("seller_id", AlipayConfig.partner);
        m.put("product_code", "QUICK_MSECURITY_PAY");
        JSONObject bizcontentJson = JSONObject.fromObject(m);

        map.put("biz_content", bizcontentJson.toString());
        //对未签名原始字符串进行签名
        String rsaSign = AlipaySignature.rsaSign(map, AlipayConfig.private_key, "utf-8");

        Map<String, String> map4 = new HashMap<String, String>();
        map4.put("app_id", AlipayConfig.app_id);
        map4.put("method", "alipay.trade.app.pay");
        map4.put("format", format);
        map4.put("charset", AlipayConfig.input_charset);
        map4.put("sign_type", AlipayConfig.sign_type);
        map4.put("timestamp", URLEncoder.encode(UtilDate.getDateFormatter(), "UTF-8"));
        map4.put("version", "1.0");
        map4.put("notify_url", URLEncoder.encode(AlipayConfig.notify_url, "UTF-8"));
        //最后对请求字符串的所有一级value（biz_content作为一个value）进行encode，编码格式按请求串中的charset为准，没传charset按UTF-8处理
        map4.put("biz_content", URLEncoder.encode(bizcontentJson.toString(), "UTF-8"));

        Map par = AlipayCore.paraFilter(map4); //除去数组中的空值和签名参数
        String json4 = AlipayCore.createLinkString(map4);   //拼接后的字符串

        json4 = json4 + "&sign=" + URLEncoder.encode(rsaSign, "UTF-8");

//        System.out.println("ali-mobile支付签名：" + json4.toString());

        return json4.toString();
    }

    /**
     * wep支付
     * Jahnke 2017年1月7日 23:53:14
     *
     * @param orderCode  订单号
     * @param pay        支付金额
     * @param activeTime 默认30m 订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
     * @param subject    商品名称
     * @param body       商品详情
     * @return
     */
    public String wap_pay(String orderCode, float pay, String activeTime, String subject, String body) throws UnsupportedEncodingException, AlipayApiException {
        //公共参数
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_id", AlipayConfig.app_id);
        map.put("method", "alipay.trade.wap.pay");
        map.put("format", format);
        map.put("charset", AlipayConfig.input_charset);
        map.put("sign_type", AlipayConfig.sign_type);
        map.put("timestamp", UtilDate.getDateFormatter());
        map.put("version", "1.0");
        map.put("notify_url", AlipayConfig.notify_url);

        Map<String, String> m = new HashMap<String, String>();
        m.put("body", body == null || body.equals("") ? "商品描述" : body);
        m.put("subject", (subject == null || subject.equals("") ? "商品" : subject));
        m.put("out_trade_no", orderCode);
        m.put("timeout_express", activeTime == null || activeTime.equals("") ? "30m" : activeTime);
        m.put("total_amount", String.valueOf(pay));
        m.put("seller_id", AlipayConfig.partner);
        m.put("product_code", "QUICK_MSECURITY_PAY");
        JSONObject bizcontentJson = JSONObject.fromObject(m);

        map.put("biz_content", bizcontentJson.toString());
        //对未签名原始字符串进行签名
        String rsaSign = AlipaySignature.rsaSign(map, AlipayConfig.private_key, "utf-8");

        Map<String, String> map4 = new HashMap<String, String>();
        map4.put("app_id", AlipayConfig.app_id);
        map4.put("method", "alipay.trade.wap.pay");
        map4.put("format", format);
        map4.put("charset", AlipayConfig.input_charset);
        map4.put("sign_type", AlipayConfig.sign_type);
        map4.put("timestamp", URLEncoder.encode(UtilDate.getDateFormatter(), "UTF-8"));
        map4.put("version", "1.0");
        map4.put("notify_url", URLEncoder.encode(AlipayConfig.notify_url, "UTF-8"));
        //最后对请求字符串的所有一级value（biz_content作为一个value）进行encode，编码格式按请求串中的charset为准，没传charset按UTF-8处理
        map4.put("biz_content", URLEncoder.encode(bizcontentJson.toString(), "UTF-8"));

        Map par = AlipayCore.paraFilter(map4); //除去数组中的空值和签名参数
        String json4 = AlipayCore.createLinkString(map4);   //拼接后的字符串

        json4 = json4 + "&sign=" + URLEncoder.encode(rsaSign, "UTF-8");

//        System.out.println("ali-mobile支付签名：" + json4.toString());

        return json4.toString();
    }

    /**
     * 二维码支付
     * Jahnke 2017年1月7日 23:53:14
     *
     * @param orderNo    订单号
     * @param pay        支付金额
     * @param activeTime 默认30m 订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
     * @param subject    商品名称
     * @param body       商品详情
     * @return
     */
    public String qr_pay(String orderNo, float pay, String activeTime, String subject, String body) throws UnsupportedEncodingException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);  //获得初始化的AlipayClient
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"total_amount\":\"" + pay + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"store_id\":\"\"," +
                "\"timeout_express\":\"" + activeTime + "\"}");//设置业务参数
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        if (null != response && "10000".equalsIgnoreCase(response.getCode())) {
            return response.getQrCode();
        }

        System.out.print("获取支付宝二维码：" + response.getBody());
        //根据response中的结果继续业务逻辑处理
        return "";
    }

    //app 支付
    public static String app_pay(String orderNo, float pay, String activeTime, String subject, String body) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setOutTradeNo(orderNo);
        model.setTimeoutExpress(activeTime);
        model.setTotalAmount(pay + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);
        AlipayTradeAppPayResponse response = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (null == response) {
            return null;
        }
        return response.getBody();
    }

    //app 支付
    public static String app_pay(String orderNo, float pay,
                                 String activeTime,
                                 String subject, String body,
                                 String appId, String privateKey,
                                 String aliPublicKey, String signType, String notifyUrl) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", AlipayConfig.input_charset, aliPublicKey, signType);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setOutTradeNo(orderNo);
        model.setTimeoutExpress(activeTime);
        model.setTotalAmount(pay + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        AlipayTradeAppPayResponse response = null;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (null == response) {
            return null;
        }
        return response.getBody();
    }

    /**
     * 关闭二维码交易
     * zhuwx
     *
     * @param orderNo    订单号
     * @param pay        支付金额
     * @param activeTime 默认30m 订单超时时间 当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。 取值范围：1m～15d(m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）)该数值不接受小数点
     * @param subject    商品名称
     * @param body       商品详情
     * @return
     */
    public String qr_close_pay(String orderNo, float pay, String activeTime, String subject, String body) throws UnsupportedEncodingException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);  //获得初始化的AlipayClient
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();//创建API对应的request类
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"total_amount\":\"" + pay + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"store_id\":\"\"," +
                "\"timeout_express\":\"" + activeTime + "\"}");//设置业务参数
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        System.out.print(response.getBody());
        //根据response中的结果继续业务逻辑处理
        return "";
    }


    /**
     * 主动查询订单-获取订单状态
     *
     * @param payOrderNo 支付宝生成的流水订单号
     * @param orderNo    订单号
     * @return
     */
    public String pay_trade_query(String payOrderNo, String orderNo) throws QueryExcetion, AlipayApiException, DataEmptyException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id,
                AlipayConfig.private_key, format, AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderNo + "\"," +
                "    \"trade_no\":\"" + (payOrderNo == null ? "" : payOrderNo) + "\"" +
                "  }");

        AlipayTradeQueryResponse response = null;
        response = alipayClient.execute(request);

//        System.out.println(AjaxResult.successResult(response));
//        System.out.println("帐号：" + response.getBuyerPayAmount());
//        System.out.println("支付金额：" +response.getTotalAmount());
//        System.out.println("交易状态:" + response.getTradeStatus());
        if (response.isSuccess()) {
            return response.getTradeStatus();
        } else if (JSONObject.fromObject(response).toString().indexOf("TRADE_NOT_EXIST") > 0) {
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".交易不存在");
//            throw new DataEmptyException("交易不存在");
        } else {
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".查询失败，请重试");
//            throw new QueryExcetion("查询失败，请重试");
        }

        return null;
    }


    /**
     * 主动查询订单-获取订单状态
     *
     * @param payOrderNo 支付宝生成的流水订单号
     * @param orderNo    订单号
     * @return 订单详细信息
     */
    public QueryResult getAliPayStatus(String payOrderNo, String orderNo) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id,
                AlipayConfig.private_key, format, AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderNo + "\"," +
                "    \"trade_no\":\"" + (payOrderNo == null ? "" : payOrderNo) + "\"" +
                "  }");


        QueryResult queryResult = new QueryResult();
        queryResult.setQuerySuccess(false);

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            queryResult.setQuerySuccess(false);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

//        System.out.println(AjaxResult.successResult(response));
//        System.out.println("帐号：" + response.getBuyerPayAmount());
//        System.out.println("支付金额：" +response.getTotalAmount());
//        System.out.println("交易状态:" + response.getTradeStatus());

        if (null == response) {
            queryResult.setQuerySuccess(false);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if (response.isSuccess()) {//查询成功
            queryResult.setQuerySuccess(true);//支付成功
            queryResult.setPaySuccess(true);//支付成功
            queryResult.setPayStatus(response.getTradeStatus());
            queryResult.setPayerId(response.getBuyerUserId());
            queryResult.setPayerAccount(response.getBuyerLogonId());
            return queryResult;
        } else if (JSONObject.fromObject(response).toString().indexOf("TRADE_NOT_EXIST") > 0) {
            queryResult.setPayStatus(TradeStatusUtils.NOT_PAY);
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".交易不存在");
            return queryResult;
        } else {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".查询失败，请重试");
            return queryResult;
        }

    }

    /**
     * 主动查询订单-获取订单状态
     *
     * @param payOrderNo 支付宝生成的流水订单号
     * @param orderNo    订单号
     * @return 订单详细信息
     */
    public QueryResult getAliPayStatus(String payOrderNo, String orderNo,
                                       String appId, String privateKey,
                                       String aliPublicKey, String signType) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId,
                privateKey, AlipayConfig.format, AlipayConfig.input_charset, aliPublicKey, signType);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderNo + "\"," +
                "    \"trade_no\":\"" + (payOrderNo == null ? "" : payOrderNo) + "\"" +
                "  }");


        QueryResult queryResult = new QueryResult();
        queryResult.setQuerySuccess(false);

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            queryResult.setQuerySuccess(false);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

//        System.out.println(AjaxResult.successResult(response));
//        System.out.println("帐号：" + response.getBuyerPayAmount());
//        System.out.println("支付金额：" +response.getTotalAmount());
//        System.out.println("交易状态:" + response.getTradeStatus());

        if (null == response) {
            queryResult.setQuerySuccess(false);
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            return queryResult;
        }

        if (response.isSuccess()) {//查询成功
            queryResult.setQuerySuccess(true);//支付成功
            queryResult.setPaySuccess(true);//支付成功
            queryResult.setPayStatus(response.getTradeStatus());
            queryResult.setPayerId(response.getBuyerUserId());
            queryResult.setPayerAccount(response.getBuyerLogonId());
            return queryResult;
        } else if (JSONObject.fromObject(response).toString().indexOf("TRADE_NOT_EXIST") > 0) {
            queryResult.setPayStatus(TradeStatusUtils.NOT_PAY);
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".交易不存在");
            return queryResult;
        } else {
            queryResult.setPayStatus(TradeStatusUtils.TRADE_PAYERROR);
            System.out.println("支付宝交易查询：payOrderNo:" + payOrderNo + ",orderNo:" + orderNo + ".查询失败，请重试");
            return queryResult;
        }

    }

    // ------------------退款


    //支付宝退款
    public ResultInfo refundV2(String sysAppKey, String orderNo, String ofcOderNo,
                               String money,
                               String appId, String privateKey,
                               String aliPublicKey, String signType) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey,
                "json", AlipayConfig.input_charset, aliPublicKey, signType);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"trade_no\":\"\"," +
                "\"refund_amount\":" + money + "," +
                "\"refund_reason\":\"正常退款\"," +
                "\"out_request_no\":\"\"," +
                "\"operator_id\":\"\"," +
                "\"store_id\":\"\"," +
                "\"terminal_id\":\"\"" +
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("支付宝退款调用失败【1】：" + orderNo + "  " + e.getErrMsg());
        }

        System.out.println("支付宝查询退款：orderNo:" + orderNo + "  ,money:" + money + "   code:" + response.getCode() + "  msg:" + response.getMsg() + "   tradeNo:" + response.getTradeNo());
        if (response.isSuccess()) {
            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
                //退款成功
                //保存退款返回的退款编号
                OrderPay.saveRefundOrderCode(orderNo, ValidateUtil.isNull(ofcOderNo) ? orderNo : ofcOderNo, response.getTradeNo(), ChannelUtils.alipay);
                return new ResultInfo();
            } else {
                //退款不成功
                System.out.println("支付宝退款失败：" + orderNo + "   ;code:" + response.getCode() + "  " + response.getMsg());
                return new ResultInfo("支付宝退款失败1:" + response.getMsg());
            }
        } else {
            String resMsg = "";
            if (null != response) {
                resMsg = response.getSubMsg() + " (" + response.getSubCode() + ")";
                System.out.println("支付宝退款调用失败【2】：" + orderNo + "，" + response.getSubCode() + "  " + response.getSubMsg());
            } else {
                resMsg = "支付宝退款失败,请稍后再试";
                System.out.println("支付宝退款调用失败【2】：" + orderNo);
            }
//            return false;
            return new ResultInfo(resMsg);
        }
    }

    // 支付宝部分退款功能
    public boolean refundPart(String orderNo, String backOrderNo,
                              String money,
                              String appId, String privateKey,
                              String aliPublicKey, String signType, boolean isUpdateRefund) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey,
                "json", AlipayConfig.input_charset, aliPublicKey, signType);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"trade_no\":\"\"," +
                "\"refund_amount\":" + money + "," +
                "\"refund_reason\":\"正常退款\"," +
                "\"out_request_no\":\"" + backOrderNo + "\"," +
                "\"operator_id\":\"\"," +
                "\"store_id\":\"\"," +
                "\"terminal_id\":\"\"" +
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("支付宝退款调用失败【1】：" + orderNo + "  " + e.getErrMsg());
        }

        System.out.println("支付宝查询退款：orderNo:" + orderNo + "  ,money:" + money + "   code:" + response.getCode() + "  msg:" + response.getMsg() + "   tradeNo:" + response.getTradeNo());
        if (response.isSuccess()) {
            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
                //退款成功
                //保存退款返回的退款编号
                if (isUpdateRefund) {
                    OrderPay.saveRefundOrderCode(orderNo, orderNo, response.getTradeNo(), ChannelUtils.alipay);
                } else {
                    OrderPay.savePartRefundOrderCode(backOrderNo, response.getTradeNo(), ChannelUtils.alipay);
                }
                return true;
            } else {
                //退款不成功
                System.out.println("支付宝退款失败：" + backOrderNo + "   ;code:" + response.getCode() + "  " + response.getMsg());
                return false;
            }
        } else {
            if (null != response) {
                System.out.println("支付宝退款调用失败【2】：" + orderNo + "，" + response.getSubCode() + "  " + response.getSubMsg());
            } else {
                System.out.println("支付宝退款调用失败【2】：" + orderNo);
            }
            return false;
        }
    }

    // 支付宝部分退款功能
    public boolean refundPart(String orderNo, String backOrderNo, String money, boolean isUpdateRefund) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key,
                "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"trade_no\":\"\"," +
                "\"refund_amount\":" + money + "," +
                "\"refund_reason\":\"正常退款\"," +
                "\"out_request_no\":\"" + backOrderNo + "\"," +
                "\"operator_id\":\"\"," +
                "\"store_id\":\"\"," +
                "\"terminal_id\":\"\"" +
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("支付宝退款调用失败【1】：" + orderNo + "  " + e.getErrMsg());
        }

        System.out.println("支付宝查询退款：orderNo:" + orderNo + "  ,money:" + money + "   code:" + response.getCode() + "  msg:" + response.getMsg() + "   tradeNo:" + response.getTradeNo());
        if (response.isSuccess()) {
            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
                //退款成功
                //保存退款返回的退款编号
                if (isUpdateRefund) {
                    // 取消订单
                    OrderPay.saveRefundOrderCode(orderNo, orderNo, response.getTradeNo(), ChannelUtils.alipay);
                } else {
                    OrderPay.savePartRefundOrderCode(backOrderNo, response.getTradeNo(), ChannelUtils.alipay);
                }
                return true;
            } else {
                //退款不成功
                System.out.println("支付宝退款失败：" + backOrderNo + "   ;code:" + response.getCode() + "  " + response.getMsg());
                return false;
            }
        } else {
            if (null != response) {
                System.out.println("支付宝退款调用失败【2】：" + orderNo + "，" + response.getSubCode() + "  " + response.getSubMsg());
            } else {
                System.out.println("支付宝退款调用失败【2】：" + orderNo);
            }
            return false;
        }
    }


    //支付宝退款
//    public boolean refund(String orderNo, String ofcOderNo, String money) {
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key,
//                "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//        request.setBizContent("{" +
//                "\"out_trade_no\":\"" + orderNo + "\"," +
//                "\"trade_no\":\"\"," +
//                "\"refund_amount\":" + money + "," +
//                "\"refund_reason\":\"正常退款\"," +
//                "\"out_request_no\":\"\"," +
//                "\"operator_id\":\"\"," +
//                "\"store_id\":\"\"," +
//                "\"terminal_id\":\"\"" +
//                "  }");
//        AlipayTradeRefundResponse response = null;
//        try {
//            response = alipayClient.execute(request);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//            System.out.println("支付宝退款调用失败【1】：" + orderNo + "  " + e.getErrMsg());
//        }
//
//        System.out.println("支付宝查询退款：orderNo:" + orderNo + "  ,money:" + money + "   code:" + response.getCode() + "  msg:" + response.getMsg() + "   tradeNo:" + response.getTradeNo());
//        if (response.isSuccess()) {
//            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
//                //退款成功
//                //保存退款返回的退款编号
//                OrderPay.saveRefundOrderCode(orderNo, ValidateUtil.isNull(ofcOderNo) ? orderNo : ofcOderNo, response.getTradeNo(), ChannelUtils.alipay);
//                return true;
//            } else {
//                //退款不成功
//                System.out.println("支付宝退款失败：" + orderNo + "   ;code:" + response.getCode() + "  " + response.getMsg());
//                return false;
//            }
//        } else {
//            if (null != response) {
//                System.out.println("支付宝退款调用失败【2】：" + orderNo + "，" + response.getSubCode() + "  " + response.getSubMsg());
//            } else {
//                System.out.println("支付宝退款调用失败【2】：" + orderNo);
//            }
//            return false;
//        }
//    }

    //支付宝退款
    public ResultInfo refundV2(String orderNo, String ofcOderNo, String money) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key,
                "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"trade_no\":\"\"," +
                "\"refund_amount\":" + money + "," +
                "\"refund_reason\":\"正常退款\"," +
                "\"out_request_no\":\"\"," +
                "\"operator_id\":\"\"," +
                "\"store_id\":\"\"," +
                "\"terminal_id\":\"\"" +
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("支付宝退款调用失败【1】：" + orderNo + "  " + e.getErrMsg());
        }

        System.out.println("支付宝查询退款：orderNo:" + orderNo + "  ,money:" + money + "   code:" + response.getCode() + "  msg:" + response.getMsg() + "   tradeNo:" + response.getTradeNo());
        if (response.isSuccess()) {
            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
                //退款成功
                //保存退款返回的退款编号
                OrderPay.saveRefundOrderCode(orderNo, ValidateUtil.isNull(ofcOderNo) ? orderNo : ofcOderNo, response.getTradeNo(), ChannelUtils.alipay);
                return new ResultInfo();
            } else {
                //退款不成功
                System.out.println("支付宝退款失败：" + orderNo + "   ;code:" + response.getCode() + "  " + response.getMsg());
                return new ResultInfo("支付宝退款失败1:" + response.getMsg());
            }
        } else {
            String resMsg = "";
            if (null != response) {
                resMsg = response.getSubMsg() + " (" + response.getSubCode() + ")";
                System.out.println("支付宝退款调用失败【2】：" + orderNo + "，" + response.getSubCode() + "  " + response.getSubMsg());
            } else {
                resMsg = "支付宝退款失败,请稍后再试";
                System.out.println("支付宝退款调用失败【2】：" + orderNo);
            }
//            return false;
            return new ResultInfo(resMsg);
        }
    }

    //支付宝退款查询
    private void refund_query(String orderNo) {

//        AlipayConfig.sign_type
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type);
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        request.setBizContent("{" +
                "\"trade_no\":\"\"," +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"out_request_no\":\"2017070321001004540230962934\"" +
                "  }");
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("支付宝查询退款：" + orderNo + "   " + response.getMsg());
        if (response.isSuccess()) {
            if ("10000".equalsIgnoreCase(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
                //退款成功

            } else {
                //退款不成功

            }
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }


    //支付宝h5支付
    public static String h5_pa2y() {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, "json",
                AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://jzmedical.cn/h5/alipay.html");
//        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"20150320010101002\"," +
                " \"total_amount\":\"88.88\"," +
                " \"subject\":\"Iphone6 16G\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
//        String form = "";
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }


        AlipayTradeWapPayResponse httpResponse = null;
        try {
            httpResponse = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        System.out.println(httpResponse.toString());


        return httpResponse.getMsg();

    }

    //支付宝h5支付
    public static String h5_pay(String orderNo, String money, String subject, String body) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.private_key, AlipayConfig.format,
                AlipayConfig.input_charset, AlipayConfig.ali_public_key, AlipayConfig.sign_type); //获得初始化的AlipayClient //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://jzmedical.cn/h5/alipay.html");
//        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderNo + "\"," +
                "    \"total_amount\":" + money + "," +
                "    \"subject\":\"" + subject + "\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");//填充业务参数
//        String form = null; //调用SDK生成表单
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody();
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        httpResponse.setContentType("text/html;charset=" +  AlipayConfig.sign_type);
//        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();

//        try {
//            System.out.println(alipayClient.execute(alipayRequest).getMsg());
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }


        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return form;
    }
}
